"""
使用MediaMTX创建RTSP服务器
MediaMTX是一个现代的RTSP/WebRTC媒体服务器
"""

import subprocess
import os
import sys
import time
import requests
import zipfile
import shutil
from pathlib import Path

class MediaMTXServer:
    def __init__(self):
        self.mtx_path = "mediamtx.exe"
        self.config_path = "mediamtx-basic.yml"  # 使用基础配置文件
        self.download_url = "https://github.com/bluenviron/mediamtx/releases/download/v1.12.3/mediamtx_v1.12.3_windows_amd64.zip"
        
    def download_mediamtx(self):
        """下载MediaMTX"""
        if os.path.exists(self.mtx_path):
            print("MediaMTX已存在")
            return True
            
        print("正在下载MediaMTX...")
        try:
            response = requests.get(self.download_url, stream=True)
            response.raise_for_status()
            
            zip_path = "mediamtx.zip"
            with open(zip_path, 'wb') as f:
                for chunk in response.iter_content(chunk_size=8192):
                    f.write(chunk)
                    
            print("正在解压...")
            with zipfile.ZipFile(zip_path, 'r') as zip_ref:
                zip_ref.extractall(".")
                
            os.remove(zip_path)
            print("MediaMTX下载完成")
            return True
            
        except Exception as e:
            print(f"下载MediaMTX失败: {e}")
            return False
            
    def create_config(self):
        """创建MediaMTX配置文件"""
        config = """# MediaMTX配置文件

# 日志级别
logLevel: info

# API配置
api: yes
apiAddress: 127.0.0.1:9997

# WebRTC配置  
webrtc: yes
webrtcAddress: :8889

# HLS配置
hls: yes
hlsAddress: :8888

# RTSP配置
rtspAddress: :8554
protocols: [tcp]

# 路径配置
paths:
  # 默认路径 - 接受任何推流
  "~^.*$":
    # 允许发布和读取
    publishUser: ""
    publishPass: ""
    readUser: ""
    readPass: ""
    
  # 摄像头流路径
  camera:
    # 从本地摄像头获取流
    source: "ffmpeg:dshow://video=HP True Vision FHD Camera"
    sourceOnDemand: yes
    
  # 测试流路径  
  test:
    # 生成测试图案
    source: "ffmpeg:testsrc2=size=640x480:rate=30"
    sourceOnDemand: yes
"""
        
        with open(self.config_path, 'w', encoding='utf-8') as f:
            f.write(config)
        print(f"配置文件已创建: {self.config_path}")
        
    def start_server(self):
        """启动MediaMTX服务器"""
        if not self.download_mediamtx():
            return False
            
        self.create_config()
        
        print("正在启动MediaMTX RTSP服务器...")
        print("配置:")
        print("  RTSP端口: 8554")
        print("  API端口: 9997") 
        print("  WebRTC端口: 8889")
        print("  HLS端口: 8888")
        print()
        print("可用的流地址:")
        print("  摄像头流: rtsp://localhost:8554/camera")
        print("  测试流: rtsp://localhost:8554/test")
        print("  自定义流: rtsp://localhost:8554/stream")
        print()
        print("Web界面: http://localhost:9997")
        print()
        print("按 Ctrl+C 停止服务器")
        
        try:
            # 启动MediaMTX
            process = subprocess.Popen([self.mtx_path, self.config_path])
            process.wait()
        except KeyboardInterrupt:
            print("\n正在停止服务器...")
            process.terminate()
        except Exception as e:
            print(f"启动失败: {e}")
            return False
            
        return True

def setup_ffmpeg_stream():
    """设置FFmpeg推流到MediaMTX"""
    print("\n要将本地摄像头推流到RTSP服务器，请在新的命令行窗口运行:")
    print("ffmpeg -f dshow -i \"video=HP True Vision FHD Camera\" -c:v libx264 -preset ultrafast -tune zerolatency -f rtsp rtsp://localhost:8554/stream")

def main():
    print("MediaMTX RTSP服务器设置")
    print("=" * 40)
    
    server = MediaMTXServer()
    
    if "--setup-stream" in sys.argv:
        setup_ffmpeg_stream()
        return
        
    try:
        server.start_server()
    except KeyboardInterrupt:
        print("\n服务器已停止")

if __name__ == "__main__":
    main()
